﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;

namespace BasicFramework.Helper
{
    public static class ObjectTracer
    {
        private static List<StackObject> objects = new List<StackObject>();

        public static List<StackObject> Objects
        {
            get { return objects; }
        }

        public static void InitializeSlimDXDebug()
        {
            SlimDX.ObjectTable.ObjectAdded += new EventHandler<SlimDX.ObjectTableEventArgs>(ObjectTable_ObjectAdded);
            SlimDX.ObjectTable.ObjectRemoved += new EventHandler<SlimDX.ObjectTableEventArgs>(ObjectTable_ObjectRemoved);
        }



        private static void ObjectTable_ObjectRemoved(object sender, SlimDX.ObjectTableEventArgs e)
        {
            IntPtr pointer = e.ComObject.ComPointer;

            StackObject o = objects.Find(x => x.Pointer == pointer);

            objects.Remove(o);

        }

        private static void ObjectTable_ObjectAdded(object sender, SlimDX.ObjectTableEventArgs e)
        {
            StackTrace trace = new StackTrace();

            objects.Add(new StackObject(e.ComObject.ToString(), e.ComObject.ComPointer, trace));

        }

        public struct StackObject
        {
            public string Name;
            public StackTrace Trace;
            public IntPtr Pointer;

            public StackObject(string name, IntPtr pointer, StackTrace trace)
            {
                Name = name;
                Pointer = pointer;
                Trace = trace;
            }
        }

        public static string ToString()
        {
            StringBuilder b = new StringBuilder();
            for (int i = 0; i < Objects.Count; i++)
            {
                b.AppendLine(i + " : " + objects[i].Name + " | " + objects[i].Pointer + " | ");
                b.AppendLine(objects[i].Trace.ToString());
                b.AppendLine();
            }
            return b.ToString();
        }


    }
}
